package models

import (
	"github.com/jinzhu/gorm"
	"time"
)

type Tag struct {
	Model

	Name string `json:"name"`
	CreatedBy string `json:"created_by"`
	ModifiedBy string `json:"modified_by"`
	State int `json:"state"`
}
var tagSlice []Tag

type TagList struct {
	Name string `json:"name"`
	CreatedBy string `json:"create_by"`
}

func (tag *Tag) BeforeCreate(scope *gorm.Scope) error {
	scope.SetColumn("CreatedOn", time.Now().Unix())

	return nil
}

func (tag *Tag) BeforeUpdate(scope *gorm.Scope) error {
	scope.SetColumn("ModifiedOn", time.Now().Unix())

	return nil
}

/**
获取 标签列表
 */
func GetTags(pageNum int,pageSize int,maps interface{})(tagList []TagList)  {
	db.Model(&Tag{}).Select("name,created_by").Where(maps).Offset(pageNum).Limit(pageSize).Scan(&tagList)
	return
}

/**
获取标签总数
 */
func GetTagsTotal(maps interface{})(count int)  {
	db.Model(&Tag{}).Where(maps).Count(&count)
	return
}
func CheckTagNameIsExist(name string) bool{
	var tag Tag
	db.Select("id").Where("name =?", name).First(&tag)
	if tag.ID >  0{
		return true
	}
	return false
}
/**
新增标签
 */
func AddTag(name string,state int, createBy string)  bool{
	db.Create(&Tag{
		Name:name,
		State:state,
		CreatedBy: createBy,
	})
	return true
}

func ExistTagByID(id int) bool {
	var tag Tag
	db.Select("id").Where("id = ?", id).First(&tag)
	if tag.ID > 0 {
		return true
	}

	return false
}

func DeleteTag(id int) bool {
	db.Where("id = ?", id).Delete(&Tag{})

	return true
}

func EditTag(id int, data interface {}) bool {
	db.Model(&Tag{}).Where("id = ?", id).Updates(data)

	return true
}

func CleanAllTag() bool {
	db.Unscoped().Where("deleted_on != ?",0).Delete(&Tag{})
	return true
}